﻿
using System;
using System.Collections.Generic;
namespace Rosieks.Web.Flow.Metadata
{
    public class ActionTransition : Transition
    {
        public ActionTransition(string action, WebflowContext context, string[] parameters)
        {
            this.To = ActionTransition.Actions[action](context, parameters);
        }

        public static Dictionary<string, Func<WebflowContext, string[], State>> Actions = new Dictionary<string, Func<WebflowContext, string[], State>>()
        {
            { "GoTo", GoTo },
            { "Back", Back },
        };

        public static bool TryParse(string actionName, WebflowContext context, out Transition transition)
        {
            transition = null;
            if (actionName.StartsWith("$"))
            {
                int actionLength = actionName.IndexOf(':');
                string action;
                string[] args = new string[0];
                if (actionLength > 0)
                {
                    action = actionName.Substring(1, actionLength - 1);
                    args = actionName.Substring(actionLength + 1, actionName.Length - actionLength - 1).Split(',');
                }
                else
                {
                    action = actionName.Substring(1, actionName.Length - 1);
                }

                transition = new ActionTransition(action, context, args);

                return true;
            }
            else
            {
                return false;
            }
        }

        private static State GoTo(WebflowContext context, string[] args)
        {
            string stateName = args[0];
            State state = context.Webflow[stateName];
            while (!string.Equals(context.History.Pop(), stateName, StringComparison.InvariantCultureIgnoreCase))
            {
                if (context.History.Count == 0)
                {
                    return null;
                }
            }

            return state;
        }

        private static State Back(WebflowContext context, string[] args)
        {
            string stateName = context.History.Pop();

            return context.Webflow[stateName];
        }
    }
}
